package cn.edu.csmzxy.rk233x.auth_system.service.impl;

import cn.edu.csmzxy.rk233x.auth_system.entity.SysRole;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysRoleMapper;
import cn.edu.csmzxy.rk233x.auth_system.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.csmzxy.rk233x.auth_system.dto.RoleDTO;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysUserRole;
import cn.edu.csmzxy.rk233x.auth_system.exception.BusinessException;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysUserRoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wumxing
 * @date 2025/10/15 9:51
 * @description  角色管理服务实现
 */

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public IPage<SysRole> selectRolePage(Page<SysRole> page, String roleName) {
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        //默认不显示超级管理员角色
        wrapper.eq(SysRole::getIsDeleted, 0)
                .ne(SysRole::getRoleName, "超级管理员")
                .like(roleName != null, SysRole::getRoleName, roleName)
                .orderByAsc(SysRole::getSort);
        return roleMapper.selectPage(page, wrapper);
    }

    @Override
    @Transactional
    public void addRole(RoleDTO roleDTO) {
        // 校验角色编码唯一性
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleCode, roleDTO.getRoleCode());
        if (roleMapper.exists(wrapper)) {
            throw new BusinessException("角色编码已存在");
        }

        SysRole role = new SysRole();
        BeanUtils.copyProperties(roleDTO, role);
        roleMapper.insert(role);
    }

    @Override
    @Transactional
    public void updateRole(Long id, RoleDTO roleDTO) {
        if (id == 1) { // 禁止修改超级管理员
            throw new BusinessException("不能修改超级管理员角色");
        }

        SysRole role = roleMapper.selectById(id);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }

        // 校验角色编码唯一性（排除当前角色）
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleCode, roleDTO.getRoleCode())
                .ne(SysRole::getId, id);
        if (roleMapper.exists(wrapper)) {
            throw new BusinessException("角色编码已存在");
        }

        BeanUtils.copyProperties(roleDTO, role);
        role.setId(id);
        roleMapper.updateById(role);
    }

    @Override
    @Transactional
    public void deleteRole(Long id) {
        if (id == 1) { // 禁止删除超级管理员
            throw new BusinessException("不能删除超级管理员角色");
        }

        // 检查是否有用户关联该角色
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getRoleId, id);
        List<SysUserRole> userRoles = userRoleMapper.selectList(wrapper);
        if (!userRoles.isEmpty()) {
            throw new BusinessException("该角色已关联用户，不能删除");
        }

        roleMapper.deleteById(id);
    }
}
